// index.js
var log = require('../../utils/log.js') // 引入微信实时日志工具

Page({
    data: {
        resumeBasicId:null,
        positionCode:'',
        powerList: [],            // 题目列表
        currentQuestionIndex: 0, // 当前显示的题目索引
        interval: null,          // 录制时长计时器ID
        elapsedMilliseconds: 0,  // 录制时长
        RECORD_TIME: 180,   // 录制时长限制
        isAnswer: 0,    // 全局录制状态
        showCustomToast: false,      // 交卷提示
        showCustomToastMessage:'1',  // 交卷提示文字
        questionText:"",             // 题目文本
        defaultQuestionUrl:'https://huadong1-win7.oss-cn-hangzhou.aliyuncs.com/hiring/ai/question/test_video.mp4',
        cameraReady: false,         // 摄像头准备状态
        videoPlayed: false,         //视频播放开关
        videoLoadFailed: false,    // 视频加载失败状态
        useDefaultVideo: false,    // 使用默认视频状态
        useFallbackVideo: false,   // 使用备用视频状态
        uploadQueue: [], // 上传队列
        isUploading: false, // 是否正在上传
        showSavingMask: false, // 控制"正在保存，请稍候..."全局遮罩的显示状态
        isSubmitting: false,  // 是否正在交卷
        submittingToastTimer: null,  // 交卷提示定时器
        buttonClickDisabled: false,  // 按钮点击防抖标志
        lastClickTime: 0,  // 上次点击时间
        submissionTimeoutId: null, // 交卷总超时定时器ID
    }, 
    cameraContext:null,
    recorderManager: null, // 录音管理器
    tempVideoFiles: {}, // 存储每道题的视频文件路径
    tempAudioFiles: {}, // 存储每道题的音频文件路径
    currentRecordingQuestionId: null, // 当前正在录制的题目ID
    recordingStatus: {}, // 记录每道题的录制状态 {questionId: {videoReady: false, audioReady: false}}
    recordingCompletionInProgress: {}, // 防止重复处理录制结束 {questionId: boolean}
    saveTimeoutId: null, // 存储5秒超时定时器的ID

    /**
     * 可以在这里初始化一些数据
     */
    onLoad: function (options) {
        // 设置实时日志过滤标签
        log.setFilterMsg('ai-interview');
        log.addFilterMsg('index-page');
        
        // 输出日志统计信息
        const logStats = log.getLogStats();
        log.info(`📊 日志系统初始化 - 实时日志: ${logStats.hasRealtimeLog ? '✅' : '❌'}, 开发环境: ${logStats.isDev ? '✅' : '❌'}, 时间: ${logStats.timestamp}`);
        
        this.cameraContext = wx.createCameraContext(); 
        const resumeBasicId = options.resumeBasicId;
        const positionCode = options.positionCode;
        this.setData({resumeBasicId,positionCode});
        const app = getApp();
        const that = this;
        
        // 初始化录音管理器并设置监听器（只设置一次）
        this.recorderManager = wx.getRecorderManager();
        this.saveTimeoutId = null;
        
        // this.recorderManager.onStop((res) => {
        //     const questionId = that.currentRecordingQuestionId;
        //     if (questionId) {
        //         log.debug(`录音结束，题目ID: ${questionId}`);
        //         // 第一步：保存音频临时文件路径
        //         that.tempAudioFiles[questionId] = res.tempFilePath;
        //         // 第二步：检查当前题目状态
        //         const currentIndex = that.data.powerList.findIndex(item => item.questionId == questionId);
        //         const answerActive = that.data.powerList[currentIndex].answerActive;
        //         // 第三步：根据状态决定后续操作
        //         if (answerActive === 2) {
        //             // 情况A：视频已经成功，音频是第二个成功的
        //             that.addToUploadQueueSingle({questionId, fileType: 'audio', filePath: res.tempFilePath});
        //         } else {
        //             // 情况B：音频是第一个成功的
        //             that.handleFirstSaveSuccess(questionId, 'audio', res.tempFilePath);
        //         }
        //     }
        // });
        
        this.getPowerList();

        // 监听内存不足告警
        wx.onMemoryWarning(function (res) {
          log.error('[MEMORY-WARNING] 收到内存不足告警', res);
        });
    },

    getPowerList: function () {
        const that = this;
        const app = getApp();
        
        wx.request({
            url: app.globalData.runTimeUrl + '/ai/list/question',
            method: 'POST',
            data: {
                resumeBasicId: this.data.resumeBasicId,
                positionCode:this.data.positionCode
            },
            success(res) {
                if (res.data.data && res.data.data.length > 0) {
                    const powerList = res.data.data.map(item => {
                        const answerAllTime = item.questionTime;
                        const answerAllTimeStr = that.formatTime(answerAllTime);
                        const answerUseTime = item.answerTime == null ? 0 : item.answerTime;
                        const answerUseTimeStr = that.formatTime(answerUseTime);
                        const answerRemainingTime = answerAllTime - answerUseTime;
                        const answerRemainingTimeStr = that.formatTime(answerRemainingTime);
                        return {
                            title: item.questionTitle,
                            question: item.content,
                            questionId: item.id,
                            questionVideoUrl: item.questionVideoUrl,
                            questionTime: item.questionTime,
                             answerActive: ((item.answerContentUrl == null || item.answerContentUrl == '' ) && (item.answerWavUrl == null || item.answerWavUrl == '')) ? 0 : 2,
                            answerAllTime: answerAllTime,
                            answerAllTimeStr: answerAllTimeStr,
                            answerUseTime: answerUseTime,
                            answerUseTimeStr: answerUseTimeStr,
                            answerRemainingTime: answerRemainingTime,
                            answerRemainingTimeStr: answerRemainingTimeStr
                        };
                    });

                    // 找到第一个未回答的问题的索引
                    let firstUnansweredIndex = powerList.findIndex(item => item.answerActive !== 2);
    
                    // 如果所有问题都已回答，则定位到最后一题
                    if (firstUnansweredIndex === -1) {
                        firstUnansweredIndex = powerList.length > 0 ? powerList.length - 1 : 0;
                    }

                    that.setData({
                        powerList: powerList,
                        currentQuestionIndex: firstUnansweredIndex,
                    }, () => {
                        that.checkAndPlayVideo();
                    });
                } else {
                    that.setData({
                        powerList: []
                    });
                    wx.showToast({
                        title: '获取题目列表为空',
                        icon: 'none'
                    });
                }
            },
            fail(err) {
                log.error('获取题目列表失败', err);
                that.setData({
                    powerList: []
                });
                wx.showToast({
                    title: '获取题目失败,请重试',
                    icon: 'none'
                });
            }
        });
    },

    selectQuestion(e) {
        // 防抖处理：检查是否在短时间内重复点击
        const now = Date.now();
        const timeDiff = now - this.data.lastClickTime;
        
        // 如果距离上次点击时间小于1秒，则忽略此次点击
        if (timeDiff < 1000) {
            log.warn('检测到快速连点，忽略此次点击');
            return;
        }
        
        // 如果按钮已被禁用，则忽略此次点击
        if (this.data.buttonClickDisabled) {
            log.warn('按钮已被禁用，忽略此次点击');
            return;
        }
        
        const questionId = this.data.powerList[this.data.currentQuestionIndex].questionId;
        const answerActive = this.data.powerList[this.data.currentQuestionIndex].answerActive;
        const questionTime = this.data.powerList[this.data.currentQuestionIndex].questionTime;
       
        // 更新最后点击时间
        this.setData({
            RECORD_TIME: questionTime,
            lastClickTime: now,
            buttonClickDisabled: true  // 禁用按钮点击
        });
        
        log.debug('点击按钮，questionId:'+questionId+",answerActive:"+answerActive);
        
        if(answerActive == 2){
            wx.showToast({
                title: '本题已完成！',
                icon: 'success', 
                duration: 2000, 
                mask: true,     
            });
            // 1秒后重新启用按钮
            setTimeout(() => {
                this.setData({
                    buttonClickDisabled: false
                });
            }, 1000);
            return;
        } else if (answerActive == 0) {
            // 开始录制前先停止视频播放并等待音频缓冲清除
            const videoContext = wx.createVideoContext('questionVideo', this);
            videoContext.stop();
            
            this.setData({
                isAnswer: 1,
            }, () => {
                // 延迟1秒开始录制，确保视频音频完全停止
                setTimeout(() => {
                    this.startRecord(questionId);
                    // 录制开始后重新启用按钮
                    this.setData({
                        buttonClickDisabled: false
                    });
                }, 1000);
            });
        } else if (answerActive == 1) {
            this.stopRecord(questionId);
        }
    },
      

    /**
     * 开始录像
     * @param {*} questionId 
     * @param {*} ctx 
     */
    startRecord: function (questionId) {
        const that = this;
        
        // 详细的状态检查和清理
        if (this.currentRecordingQuestionId) {
            if (this.currentRecordingQuestionId === questionId) {
                log.warn(`题目${questionId}已在录制中，先清理状态后重新开始`);
                // 清理当前题目的录制状态，然后继续
                this.currentRecordingQuestionId = null;
                delete this.recordingCompletionInProgress[questionId];
            } else {
                log.warn(`已有题目${this.currentRecordingQuestionId}正在录制中，忽略此次开始录制请求`);
                return;
            }
        }
        
        // 检查全局录制状态
        if (this.data.isAnswer === 1) {
            log.warn(`全局录制状态异常，重置后继续，题目ID: ${questionId}`);
            this.data.isAnswer = 0;
        }
        
        // 检查题目状态是否正确
        const currentQuestion = this.data.powerList[this.data.currentQuestionIndex];
        if (currentQuestion.questionId !== questionId || currentQuestion.answerActive !== 0) {
            log.warn(`题目状态不正确，忽略此次开始录制请求`);
            return;
        }
        
        // 强制停止之前的录制
        this.forceStopPreviousRecording();
        
        // 设置当前录制的题目ID
        this.currentRecordingQuestionId = questionId;
        
        // 初始化录制状态
        this.recordingStatus[questionId] = {
            videoReady: false,
            audioReady: false,
            recordingStartTime: Date.now(),
            retryCount: 0
        };

        // 设置音频会话模式以减少回音
        wx.setInnerAudioOption({
            mixWithOther: false,
            obeyMuteSwitch: false,
            success: () => {
                log.info('音频会话设置成功');
            },
            fail: (err) => {
                log.error('音频会话设置失败', err);
            }
        });

        // 同时开始录音
        const audioOptions = {
            duration: 300000,
            sampleRate: 16000,
            numberOfChannels: 1,
            encodeBitRate: 48000,
            format: 'wav'
        };
        this.recorderManager.start(audioOptions);

        // 开始录制视频 - 支持5分钟录制
        this.cameraContext.startRecord({
            timeout: 300000, // 5分钟最大时长
            quality: 'low',
            selfieMirror: false, // 关闭镜像
            success(res) {
                let elapsedMilliseconds = 0;
                log.info(`录像开始成功，题目ID: ${questionId}`);
                that.changeAnswer(questionId, 1);
                
                that.data.interval = setInterval(() => {
                    // 添加安全检查，防止已处理的录制被重复处理
                    if (that.recordingCompletionInProgress[questionId]) {
                        log.warn(`题目${questionId}录制已在处理中，忽略定时器回调`);
                        return;
                    }
                    
                    // 检查定时器是否已被清除（防止竞态条件）
                    if (that.data.interval === null) {
                        log.warn(`题目${questionId}定时器已清除，忽略定时器回调`);
                        return;
                    }
                    
                    elapsedMilliseconds = elapsedMilliseconds + 1;
                    let updatedPowerList = that.data.powerList.map(power => {
                        if (power.questionId == questionId) {
                            power.answerUseTime = elapsedMilliseconds;
                            // 确保剩余时间不为负数
                            power.answerRemainingTime = Math.max(0, power.answerAllTime - power.answerUseTime);
                            power.answerUseTimeStr = that.formatTime(power.answerUseTime);
                            power.answerRemainingTimeStr = that.formatTime(power.answerRemainingTime);
                        }
                        return power;
                    });
                    that.setData({
                        powerList: updatedPowerList
                    });
                    
                    // 优先检查时间是否到达3分钟，避免与摄像头自动停止冲突
                    if (elapsedMilliseconds >= that.data.RECORD_TIME) {
                        // 防止竞态：再次检查是否已在处理
                        if (that.recordingCompletionInProgress[questionId]) {
                            return;
                        }
                        
                        log.info('3分钟时间到，触发自动保存流程');
                        that.recordingCompletionInProgress[questionId] = true;
                        
                        // 关键修改：调用统一的保存流程，而不是直接设置状态
                        that.startSaveProcess(questionId);
                        return;
                    } else if (!that.cameraContext._isRecording) {
                        // 防止竞态：再次检查是否已在处理
                        if (that.recordingCompletionInProgress[questionId]) {
                            return;
                        }
                        
                        log.info('检测到录制已自动停止，触发自动保存流程');
                        that.recordingCompletionInProgress[questionId] = true;
                        
                        // 统一使用保存流程，而不是直接处理
                        that.startSaveProcess(questionId);
                        return;
                    }
                }, 1000);
            },
            fail(err) {
                log.error('录像开始失败', err);
                // 清除录制状态
                that.currentRecordingQuestionId = null;
                delete that.recordingStatus[questionId];
            },timeoutCallback(){
                log.error("录制异常退出")
            }
        });
    },

    /**
     * 停止录像
     * @param {*} questionId 
     * @param {*} ctx 
     */
    stopRecord: function (questionId) {
        // 检查是否正在录制该题目
        if (this.currentRecordingQuestionId !== questionId) {
            log.warn(`题目${questionId}未在录制中，忽略停止录制请求`);
            return;
        }
        
        // 检查是否已经在处理录制结束，防止重复调用
        if (this.recordingCompletionInProgress[questionId]) {
            log.warn(`题目${questionId}停止录制已在处理中，忽略重复调用`);
            return;
        }
        
        const answerActive = this.data.powerList[this.data.currentQuestionIndex].answerActive;
        const useTime = this.data.powerList[this.data.currentQuestionIndex].answerUseTime;
        log.info(`停止录像，题目ID: ${questionId}`);
        
        if(answerActive == 1 && useTime < 10){
            wx.showModal({
                title: '提示',
                content: '答题时间小于10s！是否确认提交？',
                success: (res) => {
                    if (res.confirm) {
                        // 用户点击确定，继续提交并跳转下一题
                        this.recordingCompletionInProgress[questionId] = true;
                        this.startSaveProcess(questionId);
                    } else if (res.cancel) {
                        // 用户点击取消，重新启用按钮
                        this.setData({buttonClickDisabled: false});
                    }
                }
            });
            return;
        }
        this.startSaveProcess(questionId);
    },

    /**
     * 保存流程的主控函数
     * @param {*} questionId 
     */
    startSaveProcess: function(questionId) {
        this.setData({buttonClickDisabled: true, showSavingMask: true});
        
        // 先调用 finishRecording 清理定时器和状态
        this.finishRecording(questionId);
        
        // 再启动5秒超时保护
        this.saveTimeoutId = setTimeout(() => {
            this.handleSaveTimeout(questionId);
        }, 5000);
    },

    /**
     * 处理首次保存成功的UI和状态变更
     * @param {*} questionId 
     * @param {*} fileType 
     * @param {*} filePath 
     */
    handleFirstSaveSuccess: function(questionId, fileType, filePath) {
        // 添加状态验证
        const currentIndex = this.data.powerList.findIndex(item => item.questionId == questionId);
        if (currentIndex === -1) {
            log.error(`handleFirstSaveSuccess: 找不到题目${questionId}`);
            return;
        }
        //等待3秒后清除5秒保存超时定时器
        clearTimeout(this.saveTimeoutId);
        //将文件信息加入上传队列
        this.addToUploadQueueSingle({questionId, fileType, filePath});
        
        // 设置题目状态为已完成
        this.changeAnswer(questionId, 2);
        // 此时才设置isAnswer=0，表示全局录制真正结束
        this.data.isAnswer = 0;
        
        // 延迟清理录制状态，给音频回调留出时间窗口
        setTimeout(() => {
            this.clearRecordingStates(questionId);
        }, 2500);
        //隐藏遮罩并启用按钮
        this.setData({showSavingMask: false, buttonClickDisabled: false});

        this.nextQuestion();
    },

    /**
     * 单文件加入上传队列
     * @param {*} fileInfo 
     */
    addToUploadQueueSingle: function(fileInfo) {
        const currentQuestionIndex = this.data.powerList.findIndex(item => item.questionId == fileInfo.questionId);
        const uploadItem = {
            questionId: fileInfo.questionId,
            currentQuestionIndex: currentQuestionIndex,
            fileType: fileInfo.fileType,
            filePath: fileInfo.filePath,
            timestamp: Date.now(),
            retryCount: 0
        };
        
        this.data.uploadQueue.push(uploadItem);
        log.info(`题目${uploadItem.questionId} ${uploadItem.fileType} 已加入上传队列，队列长度：${this.data.uploadQueue.length}`);
        
        // 如果当前没有在上传，开始处理队列
        if (!this.data.isUploading) {
            this.processUploadQueue();
        }
    },

    /**
     * 处理5秒超时
     * @param {*} questionId 
     */
    handleSaveTimeout: function(questionId) {
        const currentIndex = this.data.powerList.findIndex(item => item.questionId == questionId);
        const answerActive = this.data.powerList[currentIndex].answerActive;
        
        if (answerActive !== 2) {
            this.showSaveFailureModal(questionId);
        }
    },

    /**
     * 显示保存失败弹窗
     * @param {*} questionId 
     */
    showSaveFailureModal: function(questionId) {
        this.setData({showSavingMask: false});
        wx.showModal({
            title: '保存失败',
            content: '保存失败，请重试或跳过本题',
            showCancel: true,
            cancelText: '跳过',
            confirmText: '重试',
            success: (res) => {
                if (res.confirm) {
                    this.startSaveProcess(questionId);
                } else if (res.cancel) {
                    this.handleSkipQuestion(questionId);
                }
            }
        });
    },

    /**
     * 处理跳过问题
     * @param {*} questionId 
     */
    handleSkipQuestion: function(questionId) {
        log.info(`强制跳过题目，开始全面清理状态: ${questionId}`);
        
        // 1. 强制停止所有录制活动
        if (this.recorderManager && this.currentRecordingQuestionId === questionId) {
            try {
                this.recorderManager.stop();
                log.info(`强制停止音频录制: ${questionId}`);
            } catch (err) {
                log.warn(`停止音频录制失败: ${err}`);
            }
        }
        
        if (this.cameraContext) {
            try {
                this.cameraContext.stopRecord({
                    success: () => log.info(`强制停止视频录制成功: ${questionId}`),
                    fail: (err) => log.warn(`强制停止视频录制失败: ${err}`)
                });
            } catch (err) {
                log.warn(`停止视频录制失败: ${err}`);
            }
        }
        
        // 2. 清理所有定时器
        if (this.data.interval) {
            clearInterval(this.data.interval);
            this.data.interval = null;
            log.info(`清理录制定时器: ${questionId}`);
        }
        
        if (this.saveTimeoutId) {
            clearTimeout(this.saveTimeoutId);
            this.saveTimeoutId = null;
            log.info(`清理保存超时定时器: ${questionId}`);
        }
        
        // 3. 清理所有录制状态标志
        this.data.isAnswer = 0;
        this.currentRecordingQuestionId = null;
        delete this.recordingCompletionInProgress[questionId];
        delete this.recordingStatus[questionId];
        
        // 4. 清理临时文件引用（防止内存泄漏）
        delete this.tempVideoFiles[questionId];
        delete this.tempAudioFiles[questionId];
        
        // 5. 重置UI状态
        this.setData({
            isAnswer: 0,
            buttonClickDisabled: false,
            showSavingMask: false,
            videoPlayed: false
        });
        
        log.info(`状态清理完成，设置题目为已完成: ${questionId}`);
        
        // 6. 设置题目状态为已完成
        this.changeAnswer(questionId, 2);
        
        // 7. 发送跳过请求
        const app = getApp();
        wx.request({
            url: app.globalData.runTimeUrl + '/ai/skip?answerId=' + questionId,
            method: 'GET',
            success: (skipRes) => log.info(`Skip API call for ${questionId} successful.`, skipRes),
            fail: (err) => log.error(`Skip API call for ${questionId} failed.`, err)
        });
        
        // 8. 跳转下一题
        this.nextQuestion();
    },


    /**
     * 处理摄像头自动停止的录制
     * @param {*} questionId 
     */
    handleAutoStoppedRecording: function(questionId) {
        const that = this;
        log.info(`处理摄像头自动停止的录制，题目ID: ${questionId}`);
        
        // 停止录音
        if (that.recorderManager && that.currentRecordingQuestionId === questionId) {
            log.info(`停止录音，题目ID: ${questionId}`);
            that.recorderManager.stop();
        }
        
        // 直接清理状态并进入下一题，不等待
        that.forceCompleteRecording(questionId);
    },

    /**
     * 强制完成录制（用于异常情况的兜底）
     * @param {*} questionId 
     */
    forceCompleteRecording: function(questionId) {
        const that = this;
        log.warn(`强制完成录制，题目ID: ${questionId}`);
        
        // 防重复执行检查
        if (that.currentRecordingQuestionId !== questionId) {
            log.warn(`题目${questionId}不是当前录制题目，忽略强制完成请求`);
            return;
        }
        
        // 使用统一清理入口
        that.clearRecordingStates(questionId);
        
        // 显示提示并继续下一题
        wx.showToast({ 
            title: '答题时间已到，自动进入下一题', 
            icon: 'none',
            duration: 2000
        });
        
        // 延迟后进入下一题
        setTimeout(() => {
            that.nextQuestion();
        }, 2000);
    },

    /**
     * 统一录制状态清理函数（只清理状态，不触发其他操作）
     * @param {*} questionId 需要清理的题目ID，如果为null则清理当前录制状态
     */
    clearRecordingStates: function(questionId = null) {
        // 确保只清理指定题目的状态
        if (questionId && this.currentRecordingQuestionId === questionId) {
            log.info(`清理题目${questionId}的录制状态`);
            this.currentRecordingQuestionId = null;
            delete this.recordingCompletionInProgress[questionId];
            
            // 清理相关的录制状态和文件引用
            delete this.recordingStatus[questionId];
            // 注意：不在这里清理tempVideoFiles和tempAudioFiles，让它们在上传成功后清理
            
            log.debug(`[STATE-CLEANUP] 状态已清理，题目ID: ${questionId}`);
        } else if (!questionId && this.currentRecordingQuestionId) {
            const currentId = this.currentRecordingQuestionId;
            log.info(`清理当前录制状态，题目ID: ${currentId}`);
            this.currentRecordingQuestionId = null;
            delete this.recordingCompletionInProgress[currentId];
            
            // 清理相关的录制状态和文件引用
            delete this.recordingStatus[currentId];
            // 注意：不在这里清理tempVideoFiles和tempAudioFiles，让它们在上传成功后清理
            
            log.debug(`[STATE-CLEANUP] 状态已清理，题目ID: ${currentId}`);
        } else {
            log.warn(`clearRecordingStates: 无效的清理请求，questionId=${questionId}, currentRecordingQuestionId=${this.currentRecordingQuestionId}`);
        }
    },

    /**
     * 统一录制状态清理函数（清理状态并触发视频播放）
     * @param {*} questionId 需要清理的题目ID，如果为null则清理当前录制状态
     */
    clearRecordingStatesAndTriggerVideo: function(questionId = null) {
        const targetQuestionId = questionId || this.currentRecordingQuestionId;
        
        // 先执行基础清理
        this.clearRecordingStates(targetQuestionId);
        
        // 延迟触发视频播放检查
        if (targetQuestionId) {
            log.debug(`[STATE-CLEANUP] 触发视频播放检查，题目ID: ${targetQuestionId}`);
            setTimeout(() => {
                this.checkAndPlayVideo();
            }, 500);
        }
    },

    /**
     * 完成录制的具体逻辑
     * @param {*} questionId 
     */
    finishRecording: function(questionId) {
        const that = this;
        
        log.info(`开始处理录制结束，题目ID: ${questionId}`);
        
        // 关键修复：立即清除定时器并标记已处理，防止竞态条件
        if (this.data.interval) {
            clearInterval(this.data.interval);
            this.data.interval = null; // 设为null，防止重复清理
        }
        
        // 立即标记录制结束，防止定时器回调误触发
        this.recordingCompletionInProgress[questionId] = true;
        
        // 注意：不在这里设置isAnswer=0，等待回调成功后才改变状态
        // 重置时间显示，防止负数时间
        that.resetQuestionTimeDisplay(questionId);

        // 调用内部录制结束逻辑
        that.finishRecordingInternal(questionId);
    },

    /**
     * 内部录制结束逻辑（不包含UI状态变更）
     * @param {*} questionId 
     */
    finishRecordingInternal: function(questionId) {
        const that = this;
        
        // 同步停止录音和录像
        if (that.recorderManager && that.currentRecordingQuestionId === questionId) {
            log.debug(`即将调用 recorderManager.stop，题目ID: ${questionId}`);
            that.recorderManager.stop();
        }
        
        log.info(`即将调用 cameraContext.stopRecord，题目ID: ${questionId}`);
        
        // 统一由"保存中"遮罩的5秒定时器管理
        
        that.cameraContext.stopRecord({
            // success(res) {
            //     log.info(`cameraContext.stopRecord SUCCESS，题目ID: ${questionId}`, res);
            //     that.tempVideoFiles[questionId] = res.tempVideoPath;
                
            //     const currentIndex = that.data.powerList.findIndex(item => item.questionId == questionId);
            //     const answerActive = that.data.powerList[currentIndex].answerActive;
                
            //     if (answerActive === 2) {
            //         that.addToUploadQueueSingle({questionId, fileType: 'video', filePath: res.tempVideoPath});
            //     } else {
            //         that.handleFirstSaveSuccess(questionId, 'video', res.tempVideoPath);
            //     }
                
            //     // 正常完成时清理标志
            //     delete that.recordingCompletionInProgress[questionId];
            // },
            // fail(err) {
            //     log.error(`cameraContext.stopRecord FAIL，题目ID: ${questionId}`, err);
                
            //     const currentIndex = that.data.powerList.findIndex(item => item.questionId == questionId);
            //     const answerActive = that.data.powerList[currentIndex].answerActive;
                
            //     if (answerActive === 2) {
            //         // 音频已成功，视频失败，静默返回
            //         log.info(`音频已成功，视频失败，题目已完成，题目ID: ${questionId}`);
            //         return;
            //     }
            //     // 若状态≠2：等待"保存中"遮罩的5秒统一超时处理
            //     log.warn(`视频保存失败，等待统一超时处理，题目ID: ${questionId}`);
                
            //     // 清理录制完成标志
            //     delete that.recordingCompletionInProgress[questionId];
            // }
        });
        
        log.info(`cameraContext.stopRecord 已调用，等待回调，题目ID: ${questionId}`);
    },



    // 强制停止之前的录制
    forceStopPreviousRecording: function() {
        const prevQuestionId = this.currentRecordingQuestionId;
        if (prevQuestionId) {
            log.info(`强制停止题目${prevQuestionId}的录制`);
            
            // 停止摄像头录制
            this.cameraContext.stopRecord({
                success: (res) => {
                    log.info(`强制停止录像成功，题目${prevQuestionId}`);
                    this.tempVideoFiles[prevQuestionId] = res.tempVideoPath;
                    if (!this.recordingStatus[prevQuestionId]) {
                        this.recordingStatus[prevQuestionId] = {videoReady: false, audioReady: false};
                    }
                    this.recordingStatus[prevQuestionId].videoReady = true;
                    // 停止录音
                    if (this.recorderManager) {
                        this.recorderManager.stop();
                    } else {
                        this.checkAndUpload(prevQuestionId);
                    }
                },
                fail: (err) => {
                    log.error(`强制停止录像失败，题目${prevQuestionId}`, err);
                }
            });
            
            // 使用统一清理入口：只清理状态，不触发视频播放（因为即将开始新的录制）
            this.clearRecordingStates(prevQuestionId);
        }
    },

    // 强制停止当前录制（用于页面隐藏时）
    forceStopCurrentRecording: function() {
        const questionId = this.currentRecordingQuestionId;
        if (!questionId) return;
        
        log.info(`强制停止当前录制，题目${questionId}`);
        
        // 停止定时器
        if (this.data.interval) {
            clearInterval(this.data.interval);
        }
        
        // 停止摄像头录制
        try {
            this.cameraContext.stopRecord({
                success: (res) => {
                    log.info(`强制停止当前录像成功，题目${questionId}`);
                },
                fail: (err) => {
                    log.info(`强制停止当前录像失败，题目${questionId}`, err);
                }
            });
        } catch (e) {
            log.info('停止录像异常', e);
        }
        
        // 停止录音
        try {
            if (this.recorderManager) {
                this.recorderManager.stop();
            }
        } catch (e) {
            log.info('停止录音异常', e);
        }
        
        // 使用统一清理入口：只清理状态，不触发视频播放（因为页面即将隐藏）
        this.clearRecordingStates(questionId);
    },

    // 重置题目状态为未答题
    resetQuestionToUnanswered: function(questionId) {
        log.info(`重置题目${questionId}状态为未答题`);
        
        // 找到题目并重置状态
        const updatedPowerList = this.data.powerList.map(power => {
            if (power.questionId == questionId) {
                return {
                    ...power,
                    answerActive: 0,        // 重置为未答题
                    answerUseTime: 0,       // 重置答题时间
                    answerRemainingTime: power.answerAllTime, // 重置剩余时间
                    answerUseTimeStr: this.formatTime(0),
                    answerRemainingTimeStr: this.formatTime(power.answerAllTime)
                };
            }
            return power;
        });
        
        this.setData({
            powerList: updatedPowerList,
            isAnswer: 0,  // 重置答题状态
            videoPlayed: false  // 重置视频播放状态
        });
        
        log.info(`题目${questionId}已重置为未答题状态`);
    },



    // 处理上传队列
    processUploadQueue: function() {
        if (this.data.uploadQueue.length === 0 || this.data.isUploading) {
            return;
        }
        
        this.setData({
            isUploading: true
        });
        
        const uploadItem = this.data.uploadQueue.shift();
        log.info(`开始上传题目${uploadItem.questionId}，剩余队列：${this.data.uploadQueue.length}`);
        
        this.uploadFiles(uploadItem);
    },

    uploadFiles: function(uploadItem) {
        const that = this;
        // 直接上传，不检查文件大小和设置超时
        that.performUpload(uploadItem);
    },

    // 执行实际的上传操作
    performUpload: function(uploadItem) {
        const that = this;
        const app = getApp();
        const answerTime = that.data.powerList[uploadItem.currentQuestionIndex].answerUseTime;
        
        const formDataName = uploadItem.fileType === 'video' ? 'videoFile' : 'audioFile';
        
        wx.uploadFile({
            url: app.globalData.runTimeUrl + '/ai/upload',
            filePath: uploadItem.filePath,
            name: formDataName,
            formData: {
                answerId: uploadItem.questionId,
                answerTime: answerTime,
                type: uploadItem.fileType
            },
            success: res => {
                try {
                    const response = JSON.parse(res.data);
                    if (response.code === 500) {
                        log.error(`${uploadItem.fileType}上传失败，服务器返回500`);
                        that.handleUploadError(uploadItem.questionId, uploadItem);
                        return;
                    }
                    log.info(`题目${uploadItem.questionId} ${uploadItem.fileType} 上传成功`);
                    // 上传成功后释放资源
                    that.releaseQuestionResources(uploadItem);
                    
                    // 检查是否是最后一题且正在交卷
                    //that.checkLastQuestionUploadComplete(uploadItem.questionId);
                } catch (e) {
                    wx.hideLoading();
                    log.error(`${uploadItem.fileType}上传解析失败`, e);
                    that.handleUploadError(uploadItem.questionId, uploadItem);
                }
            },
            fail: err => {
                wx.hideLoading();
                log.error(`${uploadItem.fileType}上传失败`, err);
                that.handleUploadError(uploadItem.questionId, uploadItem);
            }
        });
    },

    // 释放题目资源
    releaseQuestionResources: function(uploadItem) {
        log.info(`释放题目${uploadItem.questionId}的资源: ${uploadItem.fileType}`);
        // 延迟删除：给微信底层更多时间
        const deleteDelay = uploadItem.fileType === 'audio' ? 5000 : 2000;
        // 主动删除临时文件，释放内存
        const filePath = uploadItem.filePath;
        
        if (filePath) {
            setTimeout(() => {
                wx.getFileSystemManager().unlink({
                    filePath: filePath,
                    success: () => log.info(`临时文件已删除: ${filePath}`),
                    fail: (err) => {
                        // 降级处理：删除失败也不影响功能
                        log.info(`文件可能仍被占用，微信将自动清理: ${filePath}`);
                    }
                });
            }, deleteDelay);
            // wx.getFileSystemManager().unlink({
            //     filePath: filePath,
            //     success: () => {
            //         log.info(`临时文件已删除: ${filePath}`);
            //     },
            //     fail: (err) => {
            //         log.warn(`删除临时文件失败: ${filePath}`, err);
            //     }
            // });
        }
        
        // 删除临时文件路径记录
        if (uploadItem.fileType === 'video' && this.tempVideoFiles[uploadItem.questionId]) {
            delete this.tempVideoFiles[uploadItem.questionId];
        }
        if (uploadItem.fileType === 'audio' && this.tempAudioFiles[uploadItem.questionId]) {
            delete this.tempAudioFiles[uploadItem.questionId];
        }
        
        // 标记上传完成，继续处理队列
        this.setData({
            isUploading: false
        });
        
        // 处理队列中的下一个任务
        setTimeout(() => {
            this.processUploadQueue();
        }, 1000);
    },

    // 检查最后一题上传完成
    checkLastQuestionUploadComplete: function(questionId) {
        // 检查是否是最后一题
        const lastQuestionId = this.data.powerList[this.data.powerList.length - 1].questionId;
        const isLastQuestion = questionId == lastQuestionId;
        
        if (isLastQuestion && this.data.isUploading) {
            log.info('最后一题上传完成，检查是否还有其他待上传内容');
            
            // 检查上传队列是否为空
            if (this.data.uploadQueue.length === 0 && !this.data.isUploading) {
                log.info('所有内容上传完成，开始页面跳转');
                
                // 隐藏交卷提示
                this.hideSubmittingToast();
                
                // 延迟500ms后跳转，确保用户能看到完成提示
                setTimeout(() => {
                    this.checkForm();
                }, 500);
            } else {
                log.info(`还有${this.data.uploadQueue.length}个文件待上传，继续等待`);
            }
        }
    },

    // 检查所有题目是否完成并且所有文件都已上传
    checkAllUploaded: function() {
        if (this.data.powerList.length === 0) {
            return; // 如果没有题目，则不执行任何操作
        }
        this.checkCompletionLoop();
    },
    checkCompletionLoop() {
        setTimeout(() => {
          const allAnswered = this.data.powerList.every(q => q.answerActive === 2);
          const uploadsFinished = this.data.uploadQueue.length === 0 && !this.data.isUploading;
      
          if (allAnswered && uploadsFinished) {
            log.info('所有题目均已回答且上传完成，跳转到表单页。');
      
            if (this.data.submissionTimeoutId) {
              clearTimeout(this.data.submissionTimeoutId);
              this.setData({ submissionTimeoutId: null });
            }
      
            this.hideSubmittingToast();
            this.checkForm();
          } else {
            log.warn(`检查完成状态：题目全部回答=${allAnswered}, 上传完成=${uploadsFinished},等3s再检查`);
            // 再等 3 秒继续检查
            this.checkCompletionLoop();
          }
        }, 3000);
      },

    // 处理上传错误
    handleUploadError: function(questionId, uploadItem) {
        log.info(`题目${questionId}上传失败，不进行重试`);
        
        // 标记上传完成，继续处理队列
        this.setData({
            isUploading: false
        });
        
        // 继续处理队列中的下一个任务
        setTimeout(() => {
            this.processUploadQueue();
        }, 1000);
    },

    /**
     * 修改答题状态
     * @param {*} questionId 
     * @param {*} answerActive 
     */
    changeAnswer: function (questionId, answerActive) {
        const currentIndex = this.data.powerList.findIndex(item => item.questionId == questionId);
        if (currentIndex === -1) {
            log.error(`changeAnswer: 找不到题目${questionId}`);
            return;
        }
        
        const oldStatus = this.data.powerList[currentIndex].answerActive;
        log.info(`状态变更: 题目${questionId} 从${oldStatus}变为${answerActive}`);
        
        // 状态变更合法性检查
        if (oldStatus === 2 && answerActive !== 2) {
            log.warn(`警告: 尝试将已完成的题目${questionId}状态从2改为${answerActive}，忽略此次变更`);
            return;
        }
        
        let updatedPowerList = this.data.powerList.map(power => {
            // 确保questionList存在且至少有一个元素
            if (power.questionId == questionId) {
                power.answerActive = answerActive;
            }
            return power;
        });
        this.setData({
            powerList: updatedPowerList // 更新data中的powerList
        });
    },
    /**
     * 在 startRecording 方法外部定义一个独立的权限检查函数
     * @param {*} callback 
     */
    checkCameraPermission: function (callback) {
        wx.getSetting({
            success(res) {
                if (!res.authSetting['scope.camera']) {
                    wx.authorize({
                        scope: 'scope.camera',
                        success() {
                            log.info('用户已授权使用相机');
                            callback(true);
                        },
                        fail() {
                            log.info('用户拒绝授权使用相机');
                            callback(false);
                        }
                    });
                } else {
                    log.info('相机权限已被授权');
                    callback(true);
                }
            },
            fail() {
                log.error('获取设置失败');
                callback(false);
            }
        });
    },
    formatTime: function (seconds) {
        // 确保秒数不为负数
        seconds = Math.max(0, seconds);
        // 计算分钟数，使用 Math.floor 来确保我们得到的是整数部分
        let minutes = Math.floor(seconds / 60);
        // 计算剩余的秒数
        let secs = seconds % 60;
        // 使用 padStart 方法来保证分钟和秒数都是两位数，不足的部分用0填充
        return `${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
    },

    /**
     * 重置题目时间显示，防止出现负数时间
     * @param {*} questionId 
     */
    resetQuestionTimeDisplay: function(questionId) {
        const that = this;
        let updatedPowerList = that.data.powerList.map(power => {
            if (power.questionId == questionId) {
                // 重置为当前实际使用时间，剩余时间为0
                power.answerRemainingTime = 0;
                power.answerRemainingTimeStr = that.formatTime(0);
            }
            return power;
        });
        that.setData({
            powerList: updatedPowerList
        });
    },

    prevQuestion() {
        if(this.data.isAnswer ==1){
            wx.showToast({
                title: '请先结束答题！',
                icon: 'success', 
                duration: 2000, 
                mask: true,     
              });
              return
        }
        let newIndex = this.data.currentQuestionIndex - 1;
        if (newIndex >= 0) {
            this.setData({
                currentQuestionIndex: newIndex,
                videoPlayed: false  // 切换题目时重置视频播放状态
            });
            // 如果题目未答题，尝试播放视频（无论摄像头是否准备好）
            if(this.data.powerList[newIndex].answerActive == 0) {
                if (this.data.cameraReady) {
                    // 摄像头已准备好，直接播放
                    const videoContext = wx.createVideoContext('questionVideo', this);
                    videoContext.play();
                    this.setData({
                        videoPlayed: true
                    });
                } else {
                    // 摄像头未准备好，启动延迟检查
                    this.delayCheckVideoPlay();
                }
            }
        }
    },
    nextQuestion: function() {
        if(this.data.isAnswer ==1){
            wx.showToast({
                title: '请先结束答题！',
                icon: 'success', 
                duration: 2000, 
                mask: true,     
              });
              return;
        }
        
        let newIndex = this.data.currentQuestionIndex + 1;

        // 循环查找下一个未回答的问题
        while (newIndex < this.data.powerList.length && this.data.powerList[newIndex].answerActive === 2) {
            log.info(`问题 ${newIndex} 已回答，跳过。`);
            newIndex++;
        }

        if (newIndex < this.data.powerList.length) {
            // 找到了下一个未回答的问题
            this.setData({
                currentQuestionIndex: newIndex,
                videoPlayed: false,
            }, () => {
                this.checkAndPlayVideo();
            });
        } else {
            // 如果没有更多未回答的问题，说明面试可能已完成
            log.info("没有更多未回答的问题，触发交卷检查。");
            this.showSubmittingToast();
            this.checkAllUploaded();
            

            // 设置一个1分钟的最终超时定时器，作为保险
            const timeoutId = setTimeout(() => {
                // 60秒后，如果定时器ID仍然存在（即未被正常流程清除），则强制跳转
                if (this.data.submissionTimeoutId === timeoutId) {
                    log.warn("交卷等待超时（1分钟），强制跳转。");
                    this.hideSubmittingToast();
                    this.checkForm();
                }
            }, 60000); // 60秒
            this.setData({ submissionTimeoutId: timeoutId });
        }
    },
    showCustomToast(message) {
        this.setData({ showCustomToast: true ,
            showCustomToastMessage:message});
        setTimeout(() => {
            this.setData({ showCustomToast: false });
        }, 2000); 
    },

    // 显示交卷中提示
    showSubmittingToast: function() {
        log.info('显示交卷中提示');
        this.setData({
            showCustomToast: true,
            showCustomToastMessage: '交卷中，请等待...'
        });
        
        // 清除之前的定时器
        if (this.data.submittingToastTimer) {
            clearTimeout(this.data.submittingToastTimer);
        }
        
        // 设置新的定时器，每3秒更新一次提示
        const updateToast = () => {
            if (this.data.isUploading) { // Changed from isSubmitting to isUploading
                this.setData({
                    showCustomToast: true,
                    showCustomToastMessage: '交卷中，请等待...'
                });
                this.data.submittingToastTimer = setTimeout(updateToast, 3000);
            }
        };
        
        this.data.submittingToastTimer = setTimeout(updateToast, 3000);
    },

    // 隐藏交卷提示
    hideSubmittingToast: function() {
        log.info('隐藏交卷中提示');
        this.setData({
            showCustomToast: false,
            isUploading: false // Changed from isSubmitting to isUploading
        });
        
        if (this.data.submittingToastTimer) {
            clearTimeout(this.data.submittingToastTimer);
            this.data.submittingToastTimer = null;
        }
    },
    // 确认是否存在表单问题
    checkForm(){
        const app = getApp();
        const resumeBasicId = this.data.resumeBasicId;
        const positionCode = this.data.positionCode;
        wx.request({
            url: app.globalData.runTimeUrl + '/ai/check/form',
            method: 'POST',
            data: { resumeBasicId: resumeBasicId,positionCode:positionCode },
            success: (res) => {
              if (res.statusCode === 200 && res.data.data) {
               wx.navigateTo({
                url: '/pages/form/form?resumeBasicId=' + resumeBasicId +'&positionCode=' + positionCode,
                 });
              } else if(res.statusCode === 200 && !res.data.data){
                wx.navigateTo({
                    url: '/pages/end/end',
                });
              }
            },
          });
    },
    onQuestionVideoEnded: function() {
        // 视频播放完毕后立即停止视频，清除音频缓冲
        const videoContext = wx.createVideoContext('questionVideo', this);
        videoContext.stop();
        
        // 短暂延迟后自动点击开始答题，确保音频完全清除
        if (this.data.powerList && this.data.powerList.length > 0 &&
            this.data.currentQuestionIndex >= 0 && this.data.currentQuestionIndex < this.data.powerList.length &&
            this.data.powerList[this.data.currentQuestionIndex].answerActive === 0) {
            setTimeout(() => {
                this.selectQuestion();
            }, 500);
        }
    },

    onVideoError: function(e) {
        log.error('视频加载失败', e);
        
        // 尝试使用备用URL
        if (!this.data.useDefaultVideo) {
            log.info('尝试使用默认视频URL');
            this.setData({ useDefaultVideo: true, videoLoadFailed: false }); // 重置失败状态以进行下一次尝试
        } else if (!this.data.useFallbackVideo) {
            log.info('尝试使用最终备用视频URL');
            this.setData({ useFallbackVideo: true, videoLoadFailed: false }); // 重置失败状态以进行下一次尝试
        } else {
            log.info('所有视频URL均加载失败');
            // 所有尝试都失败后，才最终标记为失败
            this.setData({
                videoPlayed: true, // 标记为已播放以隐藏初始加载遮罩
                videoLoadFailed: true
            });
        }
    },

    onVideoPlay: function() {
        // This function will be removed/is empty in the target state
    },

    onCameraReady: function(e) {
        // 摄像头准备就绪后，允许视频自动播放
        log.info('相机初始化完成', e.detail);
        this.setData({
            cameraReady: true
        });
        
        // 检查是否有待播放的视频或当前题目需要播放视频
        this.checkAndPlayVideo();
    },

    checkAndPlayVideo: function() {
        // 只有在摄像头准备好、视频还没播放过且当前题目未开始答题时才播放

        if (this.data.cameraReady && !this.data.videoPlayed && 
            this.data.powerList && this.data.powerList.length > 0 &&
            this.data.currentQuestionIndex >= 0 && this.data.currentQuestionIndex < this.data.powerList.length &&
            this.data.powerList[this.data.currentQuestionIndex] &&
            this.data.powerList[this.data.currentQuestionIndex].answerActive === 0) {
            const videoContext = wx.createVideoContext('questionVideo', this);
            videoContext.play();
            this.setData({
                videoPlayed: true
            });
        }
    },

    // 延迟检查视频播放的方法
    delayCheckVideoPlay: function() {
        if (!this.data.cameraReady && !this.data.videoPlayed && 
            this.data.powerList && this.data.powerList.length > 0 &&
            this.data.currentQuestionIndex >= 0 && this.data.currentQuestionIndex < this.data.powerList.length &&
            this.data.powerList[this.data.currentQuestionIndex] &&
            this.data.powerList[this.data.currentQuestionIndex].answerActive === 0) {
            
            this.setData({
                pendingVideoPlay: true
            });
            
            // 每500ms检查一次摄像头是否准备好，最多检查10次（5秒）
            let checkCount = 0;
            const checkInterval = setInterval(() => {
                checkCount++;
                if (this.data.cameraReady) {
                    clearInterval(checkInterval);
                    this.checkAndPlayVideo();
                } else if (checkCount >= 10) {
                    // 超时后强制播放
                    clearInterval(checkInterval);
                    const videoContext = wx.createVideoContext('questionVideo', this);
                    videoContext.play();
                    this.setData({
                        videoPlayed: true,
                        pendingVideoPlay: false
                    });
                }
            }, 200);
        }
    },

    onCameraError: function(e) {
        log.error('[CAMERA-ERROR] 摄像头组件底层错误:', e.detail);
        
        // 如果正在录制时摄像头出错，强制停止录制
        if (this.currentRecordingQuestionId) {
            log.error('[CAMERA-ERROR] 录制过程中摄像头出错，强制停止录制');
            this.forceCompleteRecording(this.currentRecordingQuestionId);
        }
    },

    // 页面生命周期方法
    onUnload: function () {
        log.info('页面卸载，清理录制资源');
        const app = getApp();
        const businessData = {
            resumeBasicId: this.data.resumeBasicId,
            positionCode:this.data.positionCode,
            logType:"HR0012.03",
            logContent: "页面卸载,当前正在录制题目ID="+ this.data.currentQuestionIndex
        }
        wx.request({
            url: app.globalData.runTimeUrl + '/ai/log/save',
            method: 'POST',
            data: businessData
        });

        // 清理定时器
        if (this.data.interval) {
            clearInterval(this.data.interval);
        }
        
        // 清理交卷提示定时器
        if (this.data.submittingToastTimer) {
            clearTimeout(this.data.submittingToastTimer);
        }
        
        // 清理总超时定时器
        if (this.data.submissionTimeoutId) {
            clearTimeout(this.data.submissionTimeoutId);
        }
        
        // 清理保存超时定时器
        if (this.saveTimeoutId) {
            clearTimeout(this.saveTimeoutId);
        }
        
        // 强制停止当前录制
        if (this.currentRecordingQuestionId) {
            log.info('页面卸载，强制停止录制');
            this.forceStopPreviousRecording();
        }
        
        // 使用统一清理入口：清理所有状态，不触发视频播放（因为页面即将卸载）
        this.clearRecordingStates();
        
        // 清理录音管理器
        if (this.recorderManager) {
            try {
                this.recorderManager.stop();
            } catch (e) {
                log.info('停止录音管理器失败', e);
            }
        }
        
        // 重置按钮状态
        this.setData({
            buttonClickDisabled: false,
            lastClickTime: 0
        });
    },

    onHide: function () {
        log.info('页面隐藏，处理当前录制状态');
        const app = getApp()
        const businessData = {
            resumeBasicId: this.data.resumeBasicId,
            positionCode:this.data.positionCode,
            logType:"HR0012.02",
            logContent: "页面隐藏,当前正在录制题目ID="+ this.data.currentQuestionIndex
        }
        wx.request({
            url: app.globalData.runTimeUrl + '/ai/log/save',
            method: 'POST',
            data: businessData
        });
        
        // 如果正在录制，强制停止并释放当前题目资源
        if (this.currentRecordingQuestionId) {
            const questionId = this.currentRecordingQuestionId;
            log.info(`页面隐藏时正在录制题目${questionId}，强制停止并释放资源`);
            
            // 强制停止录制
            this.forceStopCurrentRecording();
            
            // 重置当前题目状态为未答题
            this.resetQuestionToUnanswered(questionId);
        }
        
        // 检查是否有待上传的队列，如果有则继续处理
        if (this.data.uploadQueue && this.data.uploadQueue.length > 0) {
            log.info(`页面隐藏时仍有${this.data.uploadQueue.length}个文件待上传，继续处理`);
            // 不中断上传队列的处理
            if (!this.data.isUploading) {
                this.processUploadQueue();
            }
        }
        
        // 检查是否有录制完成但未上传的内容
        if (this.tempVideoFiles) {
            Object.keys(this.tempVideoFiles).forEach(questionId => {
                const videoPath = this.tempVideoFiles[questionId];
                if (videoPath) {
                    log.info(`页面隐藏时发现题目${questionId}视频文件未上传，立即处理`);
                    this.addToUploadQueueSingle({questionId, fileType: 'video', filePath: videoPath});
                }
            });
        }
        
        if (this.tempAudioFiles) {
            Object.keys(this.tempAudioFiles).forEach(questionId => {
                const audioPath = this.tempAudioFiles[questionId];
                if (audioPath) {
                    log.info(`页面隐藏时发现题目${questionId}音频文件未上传，立即处理`);
                    this.addToUploadQueueSingle({questionId, fileType: 'audio', filePath: audioPath});
                }
            });
        }

    },

    onShow: function () {
        setTimeout(() => {
            log.info('页面显示，检查录制状态');
            // 重置按钮状态，确保页面显示时按钮可用
            this.setData({
                buttonClickDisabled: false
            });

            // 添加摄像头状态轮询检查
            if (!this.data.cameraReady) {
                let checkCount = 0;
                const cameraCheckInterval = setInterval(() => {
                    checkCount++;
                    const cameraContext = wx.createCameraContext();
                    if (cameraContext && typeof cameraContext.stopRecord === 'function') {
                         // 简单地检查上下文是否存在且有方法，认为已准备好
                        clearInterval(cameraCheckInterval);
                        log.info('通过轮询检查到摄像头准备就绪');
                        this.setData({ cameraReady: true }, () => {
                            this.checkAndPlayVideo();
                        });
                    } else if (checkCount > 25) { // 超过5秒
                        clearInterval(cameraCheckInterval);
                        log.warn('摄像头轮询超时，仍未准备好');
                    }
                }, 200);
            }

            // 检查当前题目是否处于录制状态但实际没有在录制（可能是页面隐藏时中断的）
            if (this.data.powerList && this.data.powerList.length > 0 && 
                this.data.currentQuestionIndex >= 0 && this.data.currentQuestionIndex < this.data.powerList.length) {
                
                const currentQuestion = this.data.powerList[this.data.currentQuestionIndex];
                if (currentQuestion && currentQuestion.answerActive === 1 && !this.currentRecordingQuestionId) {
                    log.info(`发现当前题目${currentQuestion.questionId}状态异常，重置为未答题`);
                    this.resetQuestionToUnanswered(currentQuestion.questionId);
                }
                
                // 重新开始自动答题
                const answerActive = currentQuestion.answerActive;
                if(answerActive == 2){
                    this.nextQuestion()
                } else if(answerActive == 0) {
                    // 如果题目未答题，尝试播放视频（无论摄像头是否准备好）
                    if (this.data.cameraReady) {
                        // 摄像头已准备好，直接播放
                        const videoContext = wx.createVideoContext('questionVideo', this);
                        videoContext.play();
                        this.setData({
                            videoPlayed: true
                        });
                    } else {
                        // 摄像头未准备好，启动延迟检查
                        this.delayCheckVideoPlay();
                    }
                }
            } else {
                log.info('powerList为空或currentQuestionIndex超出范围，跳过自动答题逻辑');
            }
        }, 500);
    }
});